package org.javabasics.thread;

/**
 * Created by LUOLIANG on 2016/9/25.
 * 模拟多线程下银行取钱的操作
 */
//取钱的线程类
public class DrawThread extends Thread {
    private Account account;
    private double drawAmount;  //用户取钱所希望的钱数

    public DrawThread(String name, Account account, double drawAmount) {
        super(name);
        this.account = account;
        this.drawAmount = drawAmount;
    }

    public void run() {
//        synchronized (account) {
//            if (account.getBalance() > drawAmount) {
//                System.out.println("取钱成功！吐出钞票：" + drawAmount);
//                account.setBalance(account.getBalance() - drawAmount);
//                System.out.println("余额为：" + account.getBalance());
//            } else {
//                System.out.println(getName() + " 取钱失败！余额不足！");
//            }
//        }
        account.draw(drawAmount);
    }

    public static void main(String[] args) {
        Account account = new Account("123456", 1000);
        new DrawThread("甲", account, 800).start();
        new DrawThread("乙", account, 800).start();
    }
}

//账户类
class Account {
    private String accountNo;
    private double balance;

    public Account() {
    }

    public Account(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    //提供一个线程安全的draw方法
    public synchronized void draw(double drawAmount) {
        if (balance > drawAmount) {
            System.out.println("取钱成功！吐出钞票：" + drawAmount);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            balance -= drawAmount;
            System.out.println("余额为：" + balance);
        } else {
            System.out.println(Thread.currentThread().getName() + " 取钱失败！余额不足！");
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o != null && getClass() != o.getClass()) {
            Account target = (Account) o;
            return target.accountNo.equals(accountNo);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return accountNo.hashCode();
    }
}
